package com.huangfu.learning.javabase.java.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/7/14
 * Time: 14:42
 * Version: 1.0
 * Description: 动态代理
 **/
public class DynamicProxy {
    public static void main(String[] args) {

        //类加载器
        RealSubject realSubject = new RealSubject();
        System.out.println("类加载器：" + realSubject.getClass().getClassLoader().getClass().getName());

        //动态代理
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
        // 返回类型强转成接口类型
        Subject subject = (Subject) myInvocationHandler.bind(new RealSubject());
        String info = subject.say("huangfu", 100);
        System.out.println("info:" + info);
    }
}

interface Subject {
    String say(String name, int age);
}

class RealSubject implements Subject {

    @Override
    public String say(String name, int age) {
        return "name:" + name + "  age:" + age;
    }
}

class MyInvocationHandler implements InvocationHandler {

    private Object obj = null;

    public Object bind(Object obj) {
        //这里非常重要  设置具体对象
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object temp = method.invoke(this.obj, args);
        return temp;
    }
}